package com.xyd.wechat.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xyd.wechat.common.ApplicationConfig;
import com.xyd.wechat.common.MsgTypeEnum;
import com.xyd.wechat.service.AccessTokenService;
import com.xyd.wechat.service.CustomerService;
import com.xyd.wechat.service.MaterialService;
import com.xyd.wechat.service.MenuService;
import com.xyd.wechat.vo.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class MenuServiceImpl implements MenuService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private MaterialService materialService;

    @Autowired
    private ApplicationConfig applicationConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private ObjectMapper objectMapper;

    private static final String MEDIA_ID_DEFAULT = "wDY9v4JhMOt3Ex2LrxeajB1ZdiDwhL_6Bc2F4oQa_V4";
    private static final String MENU_MEDIA_ID = "media_id";
    private static final String MENU_VIEW = "view";
    private static final String MENU_CLICK = "click";
    private static final String NEWS_KEYWORD = "产品指引：简单几步教你轻松get“小雨点”产品操作";
    private String CONTACT_SERVICE_URL = "CONTACK_SERVICE";
    private String MENU_CLICK_TOU_SU = "MENU_CLICK_TOU_SU";


    @Scheduled(initialDelay = 10000, fixedRate = Long.MAX_VALUE)
    @Override
    public void createMenu() {
        // 构造自定义菜单参数
        // 立即借款 --> 二级菜单：产品指引
        ObjectNode introduce = objectMapper.createObjectNode();
        introduce.put("name", "产品指引");
        introduce.put("type", MENU_MEDIA_ID);
        // 获取【产品指引】图文消息ID
        String mediaId = materialService.getMediaId(MsgTypeEnum.NEWS.getType(), NEWS_KEYWORD);
        introduce.put("media_id", mediaId == null ? MEDIA_ID_DEFAULT : mediaId);
        // 立即借款 --> 二级菜单：极速借款
        ObjectNode jsjk = objectMapper.createObjectNode();
        jsjk.put("name", "极速借款");
        jsjk.put("type", MENU_VIEW);
        jsjk.put("url", "https://m.xyd.cn/");
        // 立即借款 --> 二级菜单：下载APP
        ObjectNode downloadApp = objectMapper.createObjectNode();
        downloadApp.put("name", "下载APP");
        downloadApp.put("type", MENU_VIEW);
        downloadApp.put("url", "http://a.app.qq.com/o/simple.jsp?pkgname=com.xyd.raincredit");
        // 一级菜单：立即借款
        ArrayNode arrayNode = objectMapper.createArrayNode();
        arrayNode.add(introduce);
        arrayNode.add(jsjk);
        arrayNode.add(downloadApp);
        ObjectNode immediatelyLoan = objectMapper.createObjectNode();
        immediatelyLoan.put("name", "立即借款");
        immediatelyLoan.set("sub_button", arrayNode);
        // 一级菜单：我的账户
        ObjectNode myAccount = objectMapper.createObjectNode();
        myAccount.put("name", "我的账户");
        myAccount.put("type", MENU_VIEW);
        myAccount.put("url", "https://m.xyd.cn/");
        // 帮助中心 --> 二级菜单：公司简介
        ObjectNode companyIntroduce = objectMapper.createObjectNode();
        companyIntroduce.put("name", "公司简介");
        companyIntroduce.put("type", MENU_VIEW);
        companyIntroduce.put("url", "https://m.xyd.cn/enterprise/index.html");
        // 帮助中心 --> 二级菜单：合作方式
        ObjectNode cooperation = objectMapper.createObjectNode();
        cooperation.put("name", "合作方式");
        cooperation.put("type", MENU_VIEW);
        cooperation.put("url", "https://m.xyd.cn/enterprise/cooperation.html");
        // 帮助中心 --> 二级菜单：常见问题
        ObjectNode fqa = objectMapper.createObjectNode();
        fqa.put("name", "常见问题");
        fqa.put("type", MENU_VIEW);
        fqa.put("url", "https://m.xyd.cn/static/html/helpCenter.html");
        // 帮助中心 --> 二级菜单：联系客服
        ObjectNode contactService = objectMapper.createObjectNode();
        contactService.put("name", "联系客服");
        contactService.put("type", MENU_CLICK);
        contactService.put("key", CONTACT_SERVICE_URL);
        // 帮助中心 --> 二级菜单：投诉意见
        ObjectNode tousuMenu = objectMapper.createObjectNode();
        tousuMenu.put("name", "投诉意见");
        tousuMenu.put("type", MENU_CLICK);
        tousuMenu.put("key", MENU_CLICK_TOU_SU);
        // 一级菜单：帮助中心
        ArrayNode helpArray = objectMapper.createArrayNode();
        helpArray.add(companyIntroduce);
        helpArray.add(cooperation);
        helpArray.add(fqa);
        helpArray.add(contactService);
        helpArray.add(tousuMenu);
        ObjectNode helpCenter = objectMapper.createObjectNode();
        helpCenter.put("name", "帮助中心");
        helpCenter.set("sub_button", helpArray);
        //完整菜单
        ObjectNode menu = objectMapper.createObjectNode();
        ArrayNode menuArray = objectMapper.createArrayNode();
        menuArray.add(immediatelyLoan);
        menuArray.add(myAccount);
        menuArray.add(helpCenter);
        menu.set("button", menuArray);
        //{"button":[{"name":"立即借款","sub_button":[{"name":"产品指引","type":"media_id","media_id":"产品指引：简单几步教你轻松get“小雨点”产品操作"},{"name":"极速借款","type":"view","url":"https://m.xyd.cn/"},{"name":"下载APP","type":"view","url":"http://a.app.qq.com/o/simple.jsp?pkgname=com.xyd.raincredit"}]},{"name":"我的账户","type":"view","url":"https://m.xyd.cn/"},{"name":"帮助中心","sub_button":[{"name":"公司简介","type":"view","url":"https://m.xyd.cn/enterprise/index.html"},{"name":"合作方式","type":"view","url":"https://m.xyd.cn/enterprise/cooperation.html"},{"name":"常见问题","type":"view","url":"https://m.xyd.cn/static/html/helpCenter.html"}]}]}
        logger.info("构造自定义菜单JSON参数：{}", menu.toString());
        // 请求接口创建菜单
        String url = String.format(applicationConfig.getWechatMenuCreateUrl(), accessTokenService.getAccessToken());
        logger.info("构造自定义菜单URL:{}", url);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, menu.toString(), String.class);
        logger.info("构造自定义菜单Response:{}", responseEntity.getBody());
    }

    /**
     * 点击菜单，联系客服
     *
     * @param message
     * @return
     */
    @Override
    public Message menuEventView(Message message) {
        if (CONTACT_SERVICE_URL.equalsIgnoreCase(message.getEventKey())) {
            message.setMsgType(MsgTypeEnum.TEXT.getType());
            message.setContent(applicationConfig.getWelcome());
            customerService.sendToUser(message);
        }
        if (MENU_CLICK_TOU_SU.equalsIgnoreCase(message.getEventKey())) {
            message.setMsgType(MsgTypeEnum.TEXT.getType());
            message.setContent(applicationConfig.getTousu());
            customerService.sendToUser(message);
        }
        return message;
    }
}
